﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using System.IO;

namespace JoePack
{
    public class Dependencies
    {
        private IOHelper _ioHelper;
        public Dependencies(string solutionPath)
        {
            _ioHelper = new IOHelper(solutionPath);
        }

        public static IEnumerable<string> Parse(string dependencyFilePath)
        {
            XElement xml = XElement.Load(dependencyFilePath);
            var query = from e in xml.Descendants("Dependency").Attributes("PackageName")
                        select e.Value;
            return query;

        }

        public static Dependencies Load(Catalog catalog, string solutionPath)
        {

            IEnumerable<string> packageNames = Parse(new IOHelper(solutionPath).DependenciesPath);
            var query = from p in catalog.Packages
                        join pn in packageNames on p.Name equals pn
                        select p;

            return new Dependencies(solutionPath) { Packages = new List<Package>(query) };

        }

        public List<Package> Packages { get; set; }

        public void Update()
        {
            this._ioHelper.EnsureReferenceFolderExistOrCreateNew();

            int count = 0;
            foreach (Package package in this.Packages)
            {
                count += SyncPackage(package);
                foreach (Package depPackage in package.DependentPackages)
                {
                    count += SyncPackage(depPackage);
                }
            }

            Console.WriteLine("Total updated files:{0}",count);
        }

        private int SyncPackage(Package package)
        {
            int count = 0;
            this._ioHelper.EnsurePackageFolderExistOrCreateNew(package.Name);

            foreach (File file in package.Files)
            {
                if (this._ioHelper.Sync(file))
                {
                    count++;
                }
            }
            return count;
        }
    }
}
